package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Category;
import com.ruoyi.system.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分类Controller
 *
 * @author ruoyi
 * @date 2022-04-12
 */
@RestController
@RequestMapping("/system/category")
public class CategoryController extends BaseController {
    @Autowired
    private ICategoryService categoryService;

    /**
     * 查询分类列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Category category) {
        startPage();
        List<Category> list = categoryService.selectCategoryList(category);
        return getDataTable(list);
    }

    @GetMapping("/info")
    public AjaxResult info(){
        Category category =new Category();
        List<Category> list = categoryService.selectCategoryList(category);
        List<String> nameList = new ArrayList<>();
        for (Category category1 : list) {
            nameList.add(category1.getName());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("category",nameList);
        map.put("data",list);
        return AjaxResult.success(map);
    }

    /**
     * 获取分类详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(categoryService.selectCategoryById(id));
    }

    /**
     * 新增分类
     */
    @PostMapping
    public AjaxResult add(@RequestBody Category category) {
        Category category1 = new Category();
        List<Category> list = categoryService.selectCategoryList(category1);
        Assert.isTrue(list.size()<6,"最多可添加六个");
        category.setCreateUser(SecurityUtils.getUserId().intValue());
        return toAjax(categoryService.insertCategory(category));
    }

    /**
     * 修改分类
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Category category) {
        category.setUpdateUser(SecurityUtils.getUserId().intValue());
        return toAjax(categoryService.updateCategory(category));
    }

    /**
     * 删除分类
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(categoryService.deleteCategoryByIds(ids));
    }
}
